<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧用户信息卡片 -->
      <el-col :span="6">
        <el-card class="profile-card">
          <div class="user-avatar">
            <el-avatar :size="100" :src="avatarSrc"></el-avatar>
          </div>
          <div class="user-info">
            <h2>{{ userInfo.username }}</h2>
            <p>角色: 系统管理员</p>
            <p v-if="userInfo.phone">电话: {{ userInfo.phone }}</p>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧内容区 -->
      <el-col :span="18">
        <el-card>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本资料" name="basicInfo">
              <el-form
                ref="basicFormRef"
                :model="basicForm"
                :rules="basicRules"
                label-width="100px"
              >
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="basicForm.username" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="basicForm.phone" />
                </el-form-item>
               
                <el-form-item label="头像">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="formAvatarSrc" :src="formAvatarSrc" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
                  <div class="avatar-tip">点击上传头像，支持JPG和PNG格式，大小不超过2MB</div>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateBasicInfo" :loading="loading.basic">保存更改</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="password">
              <el-form
                ref="passwordFormRef"
                :model="passwordForm"
                :rules="passwordRules"
                label-width="120px"
              >
                <el-form-item label="当前密码" prop="oldPassword">
                  <el-input v-model="passwordForm.oldPassword" type="password" show-password />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input v-model="passwordForm.newPassword" type="password" show-password />
                </el-form-item>
                <el-form-item label="确认新密码" prop="confirmPassword">
                  <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updatePassword" :loading="loading.password">修改密码</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { adminAPI } from '../../utils/api'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '../../store'

// 用户store
const userStore = useUserStore()

// 服务端地址
const serverBaseUrl = 'http://localhost:3000'
const uploadUrl = `${serverBaseUrl}/upload/avatar`
const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'

// 计算头像完整URL
const avatarSrc = computed(() => {
  // 优先使用完整URL
  if (userInfo.avatarFullUrl) return userInfo.avatarFullUrl
  // 其次使用相对路径拼接
  if (userInfo.avatar) return serverBaseUrl + userInfo.avatar
  // 最后使用默认头像
  return defaultAvatar
})

// 表单中的头像URL
const formAvatarSrc = computed(() => {
  // 优先使用完整URL
  if (basicForm.avatarFullUrl) return basicForm.avatarFullUrl
  // 没有头像则返回空
  if (!basicForm.avatar) return ''
  // 如果是完整URL则直接使用
  if (basicForm.avatar.startsWith('http')) return basicForm.avatar
  // 否则拼接服务器地址
  return serverBaseUrl + basicForm.avatar
})

// 上传头像的请求头，添加token
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${localStorage.getItem('token')}`
}))

// 当前活动标签页
const activeTab = ref('basicInfo')
const basicFormRef = ref(null)
const passwordFormRef = ref(null)
const router = useRouter()

// 加载状态
const loading = reactive({
  basic: false,
  password: false,
  profile: false
})

// 用户信息
const userInfo = reactive({
  username: '',
  phone: '',
  avatar: '',
  id: ''
})

// 基本信息表单
const basicForm = reactive({
  username: '',
  phone: '',
  avatar: '',  //头像相对路径
  avatarFullUrl: ''  //头像完整URL
})

// 基本信息表单验证规则
const basicRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单验证规则
const passwordRules = {
  oldPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur' //失去焦点时触发验证
    }
  ]
}

// 获取管理员个人资料
const loadUserProfile = async () => {
  loading.profile = true
  try {
    console.log('正在获取管理员资料...');
    console.log('当前token:', localStorage.getItem('token'));
    
    const res = await adminAPI.getProfile()
    console.log('资料请求结果:', res);
    
    if (res && res.code === 200) {
      Object.assign(userInfo, res.data)
      Object.assign(basicForm, {
        username: res.data.username,
        phone: res.data.phone || '',
        avatar: res.data.avatar || '',
        avatarFullUrl: res.data.avatarFullUrl || ''
      })
      console.log('获取资料成功:', userInfo);
      console.log('头像URL:', userInfo.avatar);
      console.log('头像完整URL:', userInfo.avatarFullUrl);
      console.log('计算的显示URL:', avatarSrc.value);
    } else {
      ElMessage.error(res?.message || '获取资料失败')
      console.error('获取资料失败:', res);
    }
  } catch (error) {
    console.error('获取资料异常:', error)
    ElMessage.error('获取资料失败，请检查网络连接')
  } finally {
    loading.profile = false
  }
}

// 上传头像前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return isJPG && isLt2M
}

// 头像上传成功回调
const handleAvatarSuccess = (res, file) => {
  if (res.code === 200) {
    // 优先使用服务器返回的完整URL（如果有）
    if (res.data.fullUrl) {
      basicForm.avatarFullUrl = res.data.fullUrl;
      console.log('使用完整URL:', res.data.fullUrl);
    }
    
    // 同时保存相对路径
    basicForm.avatar = res.data.url;
    
    console.log('上传成功，返回的信息:', res.data);
    console.log('设置头像URL为:', res.data.url);
    console.log('计算后的完整头像URL:', formAvatarSrc.value);
    
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error(res.message || '头像上传失败');
    console.error('头像上传失败:', res);
  }
}

// 更新基本信息
const updateBasicInfo = async () => {
  if (!basicFormRef.value) return
  
  await basicFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.basic = true
      try {
        // 只提交必要的数据给服务器
        console.log('提交更新的资料:', {
          username: basicForm.username,
          phone: basicForm.phone,
          avatar: basicForm.avatar
          // 注意: avatarFullUrl 不需要提交给服务器
        })
        
        const res = await adminAPI.updateProfile({
          username: basicForm.username,
          phone: basicForm.phone,
          avatar: basicForm.avatar
        })
        
        if (res.code === 200) {
          ElMessage.success('资料更新成功')
          
          // 如果服务器返回了更新后的资料，直接使用
          if (res.data) {
            // 更新本地数据
            Object.assign(userInfo, res.data)
            Object.assign(basicForm, {
              username: res.data.username,
              phone: res.data.phone || '',
              avatar: res.data.avatar || '',
              avatarFullUrl: res.data.avatarFullUrl || '' 
            })
            
            console.log('更新后的用户信息:', userInfo);
            console.log('更新后的头像URL:', userInfo.avatar);
            console.log('更新后的头像完整URL:', userInfo.avatarFullUrl);
          } else {
            // 否则重新获取资料
            loadUserProfile()
          }
          
          // 更新store中的用户信息
          userStore.updateUser({
            ...userStore.userInfo,
            username: basicForm.username,
            avatar: basicForm.avatar,
            avatarFullUrl: basicForm.avatarFullUrl
          })
        } else {
          ElMessage.error(res.message || '资料更新失败')
        }
      } catch (error) {
        console.error('更新资料异常:', error)
        ElMessage.error('更新失败，请检查网络连接')
      } finally {
        loading.basic = false
      }
    }
  })
}

// 修改密码
const updatePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.password = true
      try {
        const res = await adminAPI.updatePassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        
        if (res.code === 200) {
          ElMessage.success('密码修改成功，请重新登录')
          // 清空表单
          passwordForm.oldPassword = ''
          passwordForm.newPassword = ''
          passwordForm.confirmPassword = ''
          
          // 退出登录
          setTimeout(() => {
            userStore.logout()
            router.push('/login')
          }, 1500)
        } else {
          ElMessage.error(res.message || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改异常:', error)
        ElMessage.error('修改失败，请检查网络连接')
      } finally {
        loading.password = false
      }
    }
  })
}

// 页面加载时获取用户资料
onMounted(() => {
  loadUserProfile()
  
  // 从URL参数获取激活的标签页
  const route = useRoute()
  if (route.meta.activeTab) {
    activeTab.value = route.meta.activeTab
  }
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.profile-card {
  text-align: center;
  padding: 20px;
}

.user-avatar {
  margin-bottom: 20px;
}

.user-info h2 {
  margin-top: 0;
  margin-bottom: 10px;
}

.user-info p {
  margin: 5px 0;
  color: #606266;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.avatar-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
</style>